package com.study.ktandroid.coroutines_apply

import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import kotlinx.coroutines.Deferred
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path

val gitHubApi: GitHubApi by lazy {
    val retrofit = retrofit2.Retrofit.Builder()
        .client(OkHttpClient.Builder().addInterceptor {
            it.proceed(it.request()).apply {
                println("request:$code")
            }
        }.build())
        .baseUrl("https://api.github.com")
        .addConverterFactory(GsonConverterFactory.create())
        // retrofit配合协程使用
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .build()

    retrofit.create(GitHubApi::class.java)

}

interface GitHubApi {
    @GET("users/{login}")
    fun getUserCallBack(@Path("login") login: String): Call<User>

    @GET("users/{login}")
    suspend fun getUserSuspend(@Path("login") login: String): User

    @GET("users/{login}")
    fun getUserCallAdapterAsync(@Path("login") login: String): Deferred<User>
}

data class User(val id: String, val name: String, val url: String)